[Python] staticmethod和classmethod的区别

个人理解:

  • staticmethod:
    • 静态方法
    • 可以没有任何参数
    • 无法访问类变量实例变量
  • classmethod:
    • 类方法
    • 第一个参数必须是类本身,即cls
    • 可以访问类变量

英文解释

oop - Python @classmethod and @staticmethod for beginner?

@classmethod means: when this method is called, we pass the class as the first argument instead of the instance of that class (as we normally do with methods). This means you can use the class and its properties inside that method rather than a particular instance.

@staticmethod means: when this method is called, we don’t pass an instance of the class to it (as we normally do with methods). This means you can put a function inside a class but you can’t access the instance of that class (this is useful when your method does not use the instance).

我们来看个小例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class kls:

class_var = "I am class var"

@staticmethod
def staticm():
print(class_var)#这里会报错

@classmethod
def classm(cls): # 注意这里,第一个参数必须以cls开头
print(cls.class_var)

#普通实例方法
def instancem(self): # 注意这里,第一个参数必须以self开头
pass